package com.lily.aidouzixun.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ScrollView;

import com.lily.aidouzixun.MyApplication;
import com.lily.aidouzixun.R;
import com.lily.aidouzixun.activity.ArticleDetailActivity;
import com.lily.aidouzixun.adapter.MyListAdapter;
import com.lily.aidouzixun.adapter.MyViewHolder;
import com.lily.aidouzixun.bean.ArticleHomeInfo;
import com.lily.aidouzixun.bean.ArticleInfo;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.PullToRefreshView;
import com.lily.aidouzixun.ui.SlideShowView;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.HardWare;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.ProgressDialogUtil;
import com.lily.aidouzixun.util.T;
import com.lily.aidouzixun.webview.MyWebViewActivity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 首页Fragment
 */
public class HomeFragment extends Fragment{
    private static final String TAG = "HomeFragment";

    private DrawerLayout mDrawerLayout;
    private NavigationView mNavigationView;
    private View nvHeadView;

    private PullToRefreshView pullToRefreshView;
    private ScrollView sv;
    private ListView mListView;
    private MyListAdapter mListAdapter;
    private TitleBar mTitlebar; //标题
    private SlideShowView mSlideShowView;
    private ProgressDialog mProgressDialog;

    private static final String TITLE = "首页";
    private Context mContext;
    private Activity mActivity;
    private String key = "";
    private MyHandler mHandler;
    private int action;	//用户行为，1-得到新数据;2-得到更多数据
    private int curPageNum;
    private int totalPageNum;
    private List<ArticleInfo> longDistanceInfoList;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.longdistance_fragment, container, false);
        init();
        findViews(view);
        setListeners();
        return view;
    }

    /**
     * 初始化数据
     */
    private void init() {
        this.key += this.hashCode();
        action = 0;
        this.mContext = HomeFragment.this.getActivity();
        this.mActivity = HomeFragment.this.getActivity();
        mHandler = new MyHandler(this);
        mListAdapter = new MyListAdapter(LayoutInflater.from(mContext), MyViewHolder.HolderType.ARTICLE, mContext);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
        //得到首页数据
        getHomeData(1);
    }

    /**
     * 找到控件
     * @param view
     */
    private void findViews(View view) {
        mDrawerLayout = (DrawerLayout) view.findViewById(R.id.drawer_layout);
        mNavigationView = (NavigationView) view.findViewById(R.id.nv_menu);

        mTitlebar = (TitleBar) view.findViewById(R.id.mTitlebar);
        mTitlebar.setTitle(TITLE);
        mTitlebar.setLeftOperationVisible(false);
        mSlideShowView = (SlideShowView)view.findViewById(R.id.slideshowView);
        pullToRefreshView = (PullToRefreshView) view.findViewById(R.id.refreshable_view);
        pullToRefreshView.setNeedGetMoreData(true);
        pullToRefreshView.setNeedGetNewData(true);
        pullToRefreshView.setFootMode(PullToRefreshView.FootViewMode.ArrowShow);
        pullToRefreshView.setOnRefreshListener(refreshListener);
        sv = (ScrollView) view.findViewById(R.id.sv);
        mListView = (ListView) view.findViewById(R.id.lv_longdistance_list);
        mListView.setAdapter(mListAdapter);
        setupDrawerContent(mNavigationView);
    }

    /**
     * 设置抽屉内容
     * @param navigationView
     */
    private void setupDrawerContent(NavigationView navigationView) {
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            private MenuItem mPreMenuItem;

            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                if (mPreMenuItem != null) {
                    mPreMenuItem.setChecked(false);
                }
                menuItem.setChecked(true);
                mDrawerLayout.closeDrawers();
                mPreMenuItem = menuItem;
                return true;
            }
        });
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        /**
         * ListView Item点击监听
         */
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (HardWare.isNetworkAvailable(mContext)) {
                    ArticleInfo longDistanceInfo = longDistanceInfoList.get(i);
                    String ldid = longDistanceInfo.getLdid();
                    String param = "ldid=" + ldid;
                    ArticleDetailActivity.startWebViewActivity(mContext, longDistanceInfo, MyConstant.BASE_URL + "longdistance/itemdetail?page=1&tag=1&" + param, "文章详情", TITLE, true);
                } else {
                    T.shortToast(mContext, "请检查网络链接！");
                }
            }
        });
        //投稿的监听
        mTitlebar.setLeftOperation("投稿", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (HardWare.isNetworkAvailable(mContext)) {
                    MyWebViewActivity.startWebViewActivity(mContext, MyConstant.URLConstant.CONTRIBUTE_ARTICLES_URL, TITLE, "返回", true);
                } else {
                    T.shortToast(mContext, "请检查网络链接！");
                }
            }
        });

        /**
         * 侧滑栏监听
         */
        mTitlebar.setRightImageClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDrawerLayout.openDrawer(GravityCompat.END);
            }
        });
    }

    /**
     * 得到首页信息
     */
    private void getHomeData(int pager) {
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.LONGDISTANCE_HOME);
        param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.LONGDISTANCE_HOME);
        param.put(MyConstant.RequireParams.PAGE, pager);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 得到首页数据完成
     */
    private void getHomeFinished(ArticleHomeInfo longDistanceHomeInfo) {
        curPageNum = longDistanceHomeInfo.getCurpage();
        totalPageNum = longDistanceHomeInfo.getTotalpage();
        SparseArray<ArticleInfo> carouselList = longDistanceHomeInfo.getCarouselList();
        // todo
        // mCarouselView.setData(mContext, carouselList);
        if (action != 1 && action != 2) {   //下拉刷新会对轮播有影响，暂时屏蔽
            mSlideShowView.setData(mContext, carouselList);
        }

        if (longDistanceInfoList == null || action == 1) {
            longDistanceInfoList = new ArrayList<ArticleInfo>();
        }
        SparseArray<ArticleInfo> longDistanceInfoSparseArray = longDistanceHomeInfo.getLongDistanceItenList();
        for (int i =0; i<longDistanceInfoSparseArray.size(); i++) {
            longDistanceInfoList.add(longDistanceInfoSparseArray.get(i));
        }
        mListAdapter.setData(longDistanceInfoList);
        if (action != 1) {
            sv.smoothScrollTo(0,0);
            mListView.setFocusable(false);
        }
        mListAdapter.notifyDataSetChanged();
        pullToRefreshView.onHeaderRefreshComplete();
        pullToRefreshView.onComplete(false);
    }

    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Fragment> mFragmentReference;

        /**
         * 构造方法，传递fragment对象，防止内存泄露
         * @param fragment
         */
        MyHandler(Fragment fragment) {
            mFragmentReference = new WeakReference<Fragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final HomeFragment fragment = (HomeFragment) mFragmentReference.get();
                if(fragment !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (msg.arg1 == MyConstant.DataType.LONGDISTANCE_HOME && fragment.action == 1) {

                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (msg.arg1 == MyConstant.DataType.LONGDISTANCE_HOME && fragment.action == 1) {

                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == MyConstant.DataType.LONGDISTANCE_HOME) {
                                SparseArray<Object> carouselInfo = (SparseArray<Object>) msg.obj;
                                String errno = (String) carouselInfo.get(0);
                                if ("0".equals(errno)) {
                                    ArticleHomeInfo longDistanceHomeInfo = (ArticleHomeInfo) carouselInfo.get(2);
                                    if (longDistanceHomeInfo != null) {
                                        //处理得到首页数据完成
                                        fragment.getHomeFinished(longDistanceHomeInfo);
                                    }
                                }else{
                                    T.shortToast(fragment.mContext, "服务器正忙，请稍后再试！");
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }

    PullToRefreshView.OnRefreshListener refreshListener = new PullToRefreshView.OnRefreshListener() {

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onRefresh() {
            // TODO Auto-generated method stub
            action = 1;
            getHomeData(1);
        }

        @Override
        public boolean onMore(int nextPageNum) {
            // TODO Auto-generated method stub
            action = 2;
            if(curPageNum < totalPageNum) {
                getHomeData(curPageNum + 1);
                return true;
            } else {
                T.shortToast(mContext, "没有更多了！");
                pullToRefreshView.onComplete(false);
                return false;
            }
        }

        @Override
        public void onGetPageData() {
            // TODO Auto-generated method stub
        }

    };

}
